<style scoped lang="scss">
.commentSection {
  width: 10rem;
  height: 13rem;
  background-color: $color-white;
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 999;
  background-color: rgba(22, 24, 35, 0.98);

  .commentSection-header {
    width: 10rem;
    height: .8533rem;
    @include flex-space-between-center;
    color: $color-comment-section;
    position: absolute;
    top: 0;
    left: 0;

    i {
      font-size: .48rem;
      padding-right: .2rem;
    }

    h2 {
      font-size: .32rem;
    }
  }

  .commentSection-content {
    width: 10rem;
    height: 11rem;
    margin-top: .8533rem;

    ul {
      width: 10rem;
      height: 11rem;
      overflow: auto;

      li {
        width: 10rem;
        height: 1.84rem;

        .commentSection-content-item {
          width: 10rem;
          height: 1.84rem;
          @include flex-space-around-center;

          .commentSection-content-item-avatar {
            width: 1.0667rem;
            height: 1.0667rem;
            border-radius: 50%;
            margin-left: .2667rem;

            img {
              width: 1.0667rem;
              height: 1.0667rem;
              border-radius: 50%;
            }
          }

          .commentSection-content-item-info {
            width: 6.9333rem;
            height: 1.28rem;
            padding: .2667rem;
            @include flex-justify-center;
            flex-direction: column;

            h3 {
              font-size: .32rem;
              color: $color-comment-section;
            }

            p {
              font-size: .3733rem;
              color: $color-white;
            }

            span {
              font-size: .32rem;
              color: $color-comment-section;
            }
          }

          .commentSection-content-item-operation {
            width: 1.1733rem;
            height: 1.8133rem;
            @include flex-align-center;
            flex-direction: column;

            i {
              font-size: .48rem;
              margin-top: .2667rem;
              color: $color-comment-section;
              transition: all 0.3s ease-in-out;

            }

            p {
              font-size: .32rem;
              color: $color-comment-section;
            }
          }
        }
      }
    }
  }

  .commentSection-buttom {
    width: 10rem;
    height: 1.1733rem;
    position: absolute;
    bottom: 0;
    left: 0;
    background-color: $color-comment-section-buttom;
    @include flex-space-between-center;
    background-color: #1a1b20;

    .commentSection-buttom-left {
      width: 7.6rem;
      height: 1.1733rem;

      input {
        width: 7.6rem;
        height: 1.1733rem;
        background-color: #1a1b20;
        border: none;
        color: $color-white;
        font-size: .32rem;
        padding-left: .2667rem;
        @include input-focus-outline-none;
      }
    }

    .commentSection-buttom-right {
      width: 2.3467rem;
      height: 1.1733rem;
      display: flex;

      i {
        width: 1.1733rem;
        display: inline-block;
        height: 1.1733rem;
        color: $color-white;
        font-size: .4267rem;
        @include flex-center;
      }

    }
  }
}

.aixinactive {
  color: red !important;
  transition: all 0.3s ease-in-out;
}

@keyframes comment-section-fade-in {
  from {
    opacity: 0;
    transform: translateY(100%);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.comment-section-enter-active {
  animation: comment-section-fade-in 0.3s ease-in-out;
}

@keyframes comment-section-fade-out {
  from {
    opacity: 1;
    transform: translateY(0);
  }

  to {
    opacity: 0;
    transform: translateY(100%);
  }
}

.comment-section-leave-active {
  animation: comment-section-fade-out 0.3s ease-in-out;
}
</style>
<template>
  <Transition name="comment-section">
    <teleport to="body" v-if="showComment">
      <div class="commentSection">
        <div class="commentSection-header">
          <div></div>
          <!-- 防护：currentVideo 可能是 undefined 或 null -->
          <h2>{{ (currentVideo || []).length }}条评论</h2>
          <i @click="closeComment" class="iconfont icon-cuowuguanbiquxiao"></i>
        </div>
        <div class="commentSection-content">
          <ul>
            <!-- 关键1：加 index 兜底 key + v-if 过滤无效项 -->
            <li v-for="(item, index) in currentVideo" :key="index" <!-- 不用 item.id，避免 item 是 undefined -->
              v-if="item && item.Comment" <!-- 只渲染有 Comment 的有效项 -->
              >
              <div class="commentSection-content-item">
                <div class="commentSection-content-item-avatar">
                  <!-- 防护：userAvatar 可能不存在 -->
                  <img :src="item.Comment.userAvatar ? `http://43.138.15.137:3000${item.Comment.userAvatar}` : ''"
                    alt="用户头像">
                </div>
                <div class="commentSection-content-item-info">
                  <h3>@ {{ item.Comment.userNickname || '匿名用户' }}</h3>
                  <p>{{ item.Comment.commentContent || '无评论内容' }}</p>
                  <span>{{ item.Comment.createdAtTime || '' }}</span>
                </div>
                <!-- 关键2：点赞按钮加防护 -->
                <div class="commentSection-content-item-operation">
                  <i class="iconfont icon-aixin1" <!-- 只有 item.Comment 存在才执行点击事件 -->
                    @click="item.Comment && handleLike(
                    item.Comment.videoId,
                    item.Comment.commentId,
                    item.Comment.userId
                    )"
                    :class="{ 'aixinactive': item.Comment.isLiked }"
                    ></i>
                  <p :class="{ 'aixinactive': item.Comment.isLiked }">{{ item.likeNum || 0 }}</p>
                </div>
              </div>
            </li>
          </ul>
        </div>
        <div class="commentSection-buttom">
          <div class="commentSection-buttom-left">
            <input type="text" placeholder="有爱评论，说点儿好听的~（长按评论回复）" v-model="commentContent">
          </div>
          <div class="commentSection-buttom-right">
            <i class="iconfont icon-aite"></i>
            <!-- 关键3：提交按钮加防护 -->
            <i class="iconfont icon-dui"
              @click="currentVideo[0]?.Comment && handleSubmitComment(currentVideo[0].Comment.videoId)"></i>
          </div>
        </div>
      </div>
    </teleport>
  </Transition>
</template>
<script setup>
import { formatDateTime } from '@/utils/data';
import { useVideoInteractions } from '@/hooks/useVideoInteractions';
import { useSocketInteractions } from '@/hooks/useSocketInteractions'
const emit = defineEmits(['close', 'comment-success']);
const { sendLike, sendComment } = useSocketInteractions()

const { closeComment, commentContent, submitComment, likeComment, currentVideo } = useVideoInteractions({
  onClose: () => emit('close'),
  onCommentSuccess: () => emit('comment-success')
});

const props = defineProps({
  showComment: {
    type: Boolean,
    default: false
  },
  video: {
    type: Array,
    default: () => []
  }
})

// 关键：监听 props.video 时，过滤无效数据
watch(() => props.video, (newVal) => {
  // 1. 确保 newVal 是数组，不是就设为空数组
  const validData = Array.isArray(newVal) ? newVal : [];
  // 2. 过滤掉 undefined、null，以及没有 Comment 字段的元素
  currentVideo.value = validData.filter(item => item && item.Comment);
  // 3. 给 Comment 字段加默认值，避免缺属性
  currentVideo.value.forEach(element => {
    element.Comment.createdAtTime = formatDateTime(element.Comment.createdAt || '');
    element.Comment.isLiked = element.Comment.isLiked || false;
    element.likeNum = element.likeNum || 0;
  });
  console.log('过滤后的有效评论：', currentVideo.value);
});

function handleLike(videoId, commentId, userId) {
  // 加参数校验，避免无效参数
  if (!videoId || !commentId || !userId) return;
  sendLike({ toUserId: userId });
  likeComment(videoId, commentId);
}

function handleSubmitComment(videoId) {
  // 加参数校验
  if (!videoId || !commentContent.value.trim()) return;
  sendComment({ toVideoId: videoId });
  submitComment(videoId, commentContent.value.trim());
}
</script>